﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Kugar.Tool.Web.RequestFieldValidation.Rules
{
    public class EMailRule: RuleBase
    {
        public EMailRule(string errorMsg) : base(errorMsg)
        {
        }

        protected override string BuildDefaultErrorMessage(IRequestField field)
        {
            return Localizer["{0}必须符合EMail规则", field.Title];// $"{field.Title}必须符合EMail规则";
        }

        private static Regex _regex=new Regex(@"^([\w-_]+(?:\.[\w-_]+)*)@((?:[a-z0-9]+(?:-[a-zA-Z0-9]+)*)+\.[a-z]{2,6})$",RegexOptions.Compiled & RegexOptions.IgnoreCase);
        protected override bool ValidateField(IRequestField field)
        {
            var f = (IRequestField<string>)field;

            var value = f.Value();

            if (string.IsNullOrWhiteSpace(value))
            {
                return true;
            }

            return _regex.IsMatch(value);
        }
    }
}
